<template>
  <el-row>
    <!-- 个人信息输入区域 -->
    <div>
      <el-input
        v-model="data.user.userId"
        class="UID"
        placeholder="Please input"
        disabled
      >
        <template #prepend>UID</template>
      </el-input>
    </div>

    <div>
      <el-input v-model="data.user.username" class="username" placeholder="Please input">
        <template #prepend>用户名</template>
      </el-input>
    </div>

    

    <div>
      <el-input v-model="data.user.realname" class="realname" placeholder="Please input">
        <template #prepend>真实姓名</template>
      </el-input>
    </div>

    <div>
      <el-input v-model="data.user.place" class="address" placeholder="Please input">
        <template #prepend>住址</template>
      </el-input>
    </div>
    <div>
      <el-input v-model="data.user.phone" class="phone" placeholder="Please input">
        <template #prepend>电话</template>
      </el-input>
    </div>
    <div>
      <el-input v-model="data.user.birth" class="birth" placeholder="Please input">
        <template #prepend>出生日期</template>
      </el-input>
    </div>
    <div>
      <el-input
        v-model="data.user.pwd"
        class="password"
        placeholder="Please input"
        disabled
      >
        <template #prepend>密码</template>
      </el-input>
    </div>

    <el-button plain @click="dialogFormVisible = true" class="button"> 修改密码 </el-button>

    <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
      <el-form :model="form">
        <el-form-item label="修改后的密码" :label-width="formLabelWidth">
          <el-input
            v-model="form.newPassword"
            autocomplete="off"
            placeholder="请输入密码"
            type="password"
          />
        </el-form-item>
        <el-form-item label="确认密码" :label-width="formLabelWidth">
          <el-input
            v-model="form.confirmPassword"
            autocomplete="off"
            placeholder="请再次输入密码"
            type="password"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handlePasswordChange"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>

    <h1 class="sub-title">个人信息</h1>

    <div class="demo-basic--circle">
      <div class="block">
        <el-upload
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
          class="avatar-uploader"
        >
          <img v-if="data.user.picture" :src="data.user.picture" class="avatar-circle" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </div>
    </div>
    <el-col
      ><el-button plain type="success" @click="handleSubmit" class="commit-button"
        >提交</el-button
      ></el-col
    >
  </el-row>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";
import axios from "axios";
import OSS from "ali-oss";

const dialogFormVisible = ref(false);
const formLabelWidth = "140px";

const form = reactive({
  newPassword: "",
  confirmPassword: "",
});

const again = reactive({
  name: "",
  region: "",
  date1: "",
  date2: "",
  delivery: false,
  type: [],
  resource: "",
  desc: "",
});

const fileList = ref([]);
const circleUrl = ref("");

// 调试信息
const logDebugInfo = (message, data) => {
  console.log(`[DEBUG] ${message}:`, data);
};

const client = new OSS({
  region: "oss-cn-hangzhou", // 示例：'oss-cn-hangzhou'，填写Bucket所在地域。
  accessKeyId: "LTAI5tCg63Rt2e66w1TwnZXd", // 确保已设置环境变量OSS_ACCESS_KEY_ID。
  accessKeySecret: "8T1uwLBJsxh55WBktU9T8kKrLz8Ue5", // 确保已设置环境变量OSS_ACCESS_KEY_SECRET。
  bucket: "xmsx-dlxf", // 示例：'my-bucket-name'，填写存储空间名称。
});

const handleAvatarSuccess = (response, file) => {
  logDebugInfo("上传成功", response);
  circleUrl.value = response.url;
  data.user.picture = response.url; // 更新用户对象中的picture字段
  localStorage.setItem("user", JSON.stringify(data.user)); // 存储到本地
};

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("头像图片必须是 JPG 或 PNG 格式!");
    return false;
  }
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("头像图片大小不能超过 2MB!");
    return false;
  }
  uploadAndDownloadFile(rawFile);
  return false;
};

async function uploadAndDownloadFile(rawFile) {
  try {
    const uploadResult = await client.put(`${rawFile.name}`, rawFile);
    logDebugInfo("上传成功", uploadResult);
    circleUrl.value = uploadResult.url;
    data.user.picture = uploadResult.url; // 更新用户对象中的picture字段
    localStorage.setItem("user", JSON.stringify(data.user)); // 存储到本地
  } catch (error) {
    logDebugInfo("发生错误", error);
    if (error.code === "AccessDenied") {
      ElMessage.error("访问被拒绝，请检查你的权限配置");
    } else {
      ElMessage.error("上传失败，请稍后重试");
    }
  }
}

let data = reactive({
  user: {
    userId: "",
    username: "",
    addtime: "",
    realname: "",
    place: "",
    phone: "",
    birth: "",
    pwd: "",
    picture: "", // 添加picture字段
  },
});

onMounted(async () => {
  let localUser = localStorage.getItem("user");

  if (localUser) {
    let user = JSON.parse(localUser);
    data.user = user;
  } else {
    try {
      const response = await axios.get("http://localhost:8080/user/getUser");
      data.user = response.data.data;
    } catch (error) {
      console.error("Failed to fetch user data:", error);
    }
  }
});

const handleSubmit = async () => {
  try {
    await axios.post("http://localhost:8080/user/update", data.user);
    console.log("用户信息修改成功");
    ElMessage.success("用户信息修改成功");
  } catch (error) {
    console.error("Failed to update user data:", error);
    ElMessage.error("用户信息修改失败，请稍后重试");
  }
};

const handlePasswordChange = async () => {
  if (form.newPassword !== form.confirmPassword) {
    ElMessage.error("两次输入的密码不一致");
    return;
  }

  try {
    const response = await axios.post("http://localhost:8080/user/updatePassword", {
      userId: data.user.userId,
      newPassword: form.newPassword,
    });
    if (response.data.code === 0) {
      ElMessage.success("密码修改成功");
      data.user.pwd = form.newPassword; // 更新用户对象中的密码字段
      localStorage.setItem("user", JSON.stringify(data.user)); // 存储到本地
      dialogFormVisible.value = false; // 关闭对话框
    } else {
      ElMessage.error("密码修改失败，请稍后重试");
    }
  } catch (error) {
    console.error("Failed to change password:", error);
    ElMessage.error("密码修改失败，请稍后重试");
  }
};
</script>

<style scoped>
.sub-title {
  margin-top: 40px;
  margin-left: 565px;
}

.block {
  position: absolute;
  margin-top: 120px;
  margin-left: -135px;
}

.avatar-circle {
  border-radius: 50%;
  width: 140px;
  height: 140px;
  object-fit: cover;
  border: 2px solid #d9d9d9;
}

.avatar-uploader {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 150px;
  height: 150px;
  border: 2px dashed #d9d9d9;
  border-radius: 50%;
  cursor: pointer;
  transition: border-color 0.3s;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

.username {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 360px;
  margin-left: 250px;
}

.UID {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 270px;
  margin-left: 250px;
}

.realname {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 450px;
  margin-left: 250px;
}

.phone {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 450px;
  margin-left: 700px;
}

.address {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 360px;
  margin-left: 700px;
}



.birth {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 270px;
  margin-left: 700px;
}

.password {
  position: absolute;
  width: 300px;
  height: 40px;
  margin-top: 540px;
  margin-left: 250px;
}

.button {
  width: 130px;
  height: 40px;
  position: absolute;
  margin-top: 540px;
  margin-left: 700px;
}

.commit-button {
  width: 130px;
  height: 40px;
  position: absolute;
  margin-top: 295px;
  margin-left: 126%;
}
</style>
